<script setup lang="ts">
import { ref, watch } from "vue";
import { useColumns } from "./columns";
import Plus from "~icons/ep/plus";
import "plus-pro-components/es/components/search/style/css";
import "plus-pro-components/es/components/dialog-form/style/css";
import {
  PlusSearch,
  type FieldValues,
  PlusDialogForm,
  type PlusColumn
} from "plus-pro-components";
import { router } from "@/router";
import { ElMessage } from "element-plus";
import { isAllEmpty } from "@pureadmin/utils";
import { resetPwd, addAdminPost } from "@/api/admin";
import { getRoleList } from "@/api/system";

defineOptions({
  name: "SystemAdmin"
});

const addAdmin = () => {
  values.value = {};
  visible.value = true;
};

const searchColumns: PlusColumn[] = [
  {
    label: "搜索",
    width: 100,
    prop: "keyWord",
    valueType: "copy",
    tooltip: "请输入搜索关键词"
  },
  {
    label: "状态",
    prop: "status",
    valueType: "select",
    tooltip: "请选择新闻类目",
    options: [
      {
        label: "启用",
        value: 1,
        color: "red"
      },
      {
        label: "禁用",
        value: 0,
        color: "red"
      }
    ]
  }
];

const {
  loading,
  columns,
  dataList,
  pagination,
  loadingConfig,
  adaptiveConfig,
  loadData,
  onSizeChange,
  onKeywordChange,
  onCurrentChange
} = useColumns();
function detailClick(row) {
  console.log(
    "%crow===详情>>>: ",
    "color: MidnightBlue; background: Aquamarine; font-size: 20px;",
    row
  );
  router.push({ name: "UserDetail", query: { id: row.id } });
}
function editClick(row) {
  console.log(
    "%crow===编辑>>>: ",
    "color: MidnightBlue; background: Aquamarine; font-size: 20px;",
    row
  );
}

const defaultSearchState = ref({});

const handleSearch = (value: any) => {
  console.log(value, "search");
  onKeywordChange(value);
};
const handleReset = value => {
  console.log("reset");
  onKeywordChange(value);
};

const handleChange = (value: any, target: any) => {
  console.log("change", value);
  if (target.prop == "keyWord") {
    return;
  }
  onKeywordChange(value);
};

const confirmResetPwdClick = async row => {
  console.log("reset", row);
  try {
    const res = await resetPwd(row.id);
    ElMessage.success("重置成功");
  } catch (error) {
    console.log(error, "error");
  }
};

const visible = ref(false);
const values = ref<FieldValues>({});

const formColumns: PlusColumn[] = [
  {
    label: "登录账号",
    prop: "loginName",
    valueType: "input",
    tooltip: "请输入登录账号"
  },
  {
    label: "用户姓名",
    prop: "userName",
    valueType: "input"
  },
  {
    label: "用户手机号",
    prop: "mobile",
    valueType: "input"
  },
  ,
  {
    label: "角色",
    prop: "roleId",
    valueType: "select",
    options: async () => {
      try {
        const res = await getRoleList();
        return res.data.map(item => ({
          label: item.role_name,
          value: item.id
        }));
      } catch (error) {
        console.log("error", error);
        return [];
      }
    }
  }
];
const rules = {
  loginName: [
    {
      required: true,
      message: "登录账号必填"
    }
  ],
  userName: [
    {
      required: true,
      message: "用户姓名必填"
    }
  ],
  mobile: [
    {
      required: true,
      message: "用户手机必填"
    }
  ],
  roleId: [
    {
      required: true,
      message: "用户角色必选"
    }
  ]
};
const confirmLoading = ref(false);
const handleSubmit = async (value: FieldValues) => {
  const updatedValues = { ...values.value };
  confirmLoading.value = true;
  try {
    await addAdminPost(updatedValues);
    visible.value = false;
    confirmLoading.value = false;
    formRef.value?.formInstance?.resetFields();
    ElMessage.success("添加成功");
    loadData();
  } catch (error) {
    confirmLoading.value = false;
    console.log("error", error);
  }
};
const formRef = ref();
</script>

<template>
  <ElCard>
    <template #header>
      <ElPageHeader :icon="null">
        <template #title>
          <h3>管理员管理</h3>
        </template>
        <template #extra>
          <div class="flex flex-row items-end justify-end">
            <el-button type="primary" @click="addAdmin">
              <el-icon :size="15" color="#fff">
                <IconifyIconOffline :icon="Plus" />
              </el-icon>
              添加管理员
            </el-button>
          </div>
        </template>
        <PlusSearch
          :defaultValues="defaultSearchState"
          class="mt-5"
          :hasUnfold="false"
          :columns="searchColumns"
          @reset="handleReset"
          @search="handleSearch"
          @change="handleChange"
        />
      </ElPageHeader>
    </template>
    <pure-table
      ref="tableRef"
      showOverflowTooltip
      border
      adaptive
      :adaptiveConfig="adaptiveConfig"
      row-key="id"
      alignWhole="center"
      :loading="loading"
      :loading-config="loadingConfig"
      :data="dataList"
      :columns="columns"
      :pagination="pagination"
      @page-size-change="onSizeChange"
      @page-current-change="onCurrentChange"
    >
      <template #operation="{ row }">
        <el-popconfirm
          class="box-item"
          title="确定重置密码吗？"
          placement="top"
          @confirm="confirmResetPwdClick(row)"
        >
          <template #reference>
            <el-button type="danger" size="small"> 重置密码 </el-button>
          </template>
        </el-popconfirm>
      </template>
    </pure-table>
    <PlusDialogForm
      ref="formRef"
      v-model:visible="visible"
      v-model="values"
      :form="{ columns: formColumns, rules, labelWidth: 120 }"
      :dialog="{ confirmLoading }"
      title="添加管理员"
      @confirm="handleSubmit"
    />
  </ElCard>
</template>

<style scoped></style>
